import java.util.Deque;
import java.util.LinkedList;

import javax.imageio.plugins.tiff.FaxTIFFTagSet;

import org.w3c.dom.Node;

/*
 * @lc app=leetcode.cn id=116 lang=java
 *
 * [116] 填充每个节点的下一个右侧节点指针
 */

// @lc code=start
/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

class Solution {
    public Node connect(Node root) {
        //O(N)复杂度
        if(root==null) return null;
        Deque<Node> que=new LinkedList<>();
        que.offer(root);
        while(!que.isEmpty()){
            int size=que.size();
            for(int i=0;i<size;i++){
                Node front=que.poll();
                if(i<size-1){
                    front.next=que.peek();//i=size-1时不用处理，因为默认next就是null！所以正常就是同一层队头不断指向下一个队头即可
                }
                if(front.left!=null){
                    que.offer(front.left);
                }
                if(front.right!=null){
                    que.offer(front.right);
                }
            }
        }
        return root;  
    }
}
// @lc code=end

